package com.wanlian.router.ui.router;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.lowett.android.qrcode.manager.ScannerFragment;
import com.smart.android.ui.BaseActivity;
import com.smart.android.ui.app.IntentExtra;
import com.wanlian.router.R;
import com.wanlian.router.net.NetWorkingClient;
import com.wanlian.router.net.ResponseData;
import com.wanlian.router.net.internal.INetCallBack;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Hyu on 2018/9/12.
 * Email: fvaryu@qq.com
 */
public class BindDeviceActivity extends BaseActivity implements ScannerFragment.OnScannerSuccessListener{

    @BindView(R.id.tv_next)
    TextView mNext;

    private String qrCode;

    private ScannerFragment mScannerFragment;

    public static void go(Context context, boolean fromLogin) {
        Intent intent = new Intent(context, BindDeviceActivity.class);
        intent.putExtra(IntentExtra.EXTRA_BOOL, fromLogin);
        context.startActivity(intent);
    }

    @Override
    protected int layout() {
        return R.layout.activity_bind_device;
    }


    @Override
    public void initUI() {
        super.initUI();
        setTitle(formLogin() ? "绑定设备" : "绑定新设备");
    }

    @Override
    public void initData() {
        super.initData();
        mScannerFragment = new ScannerFragment();
        mScannerFragment.setOnScannerSuccessListener(this);
        mScannerFragment.setTipTextA("请扫描路由器机身二维码");
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment, mScannerFragment, "scann")
                .commit();

        mNext.setVisibility(formLogin() ? View.GONE : View.VISIBLE);
    }


    boolean formLogin() {
        return getIntent().getBooleanExtra(IntentExtra.EXTRA_BOOL, false);
    }

    @OnClick(R.id.tv_next)
    void next() {

        NetWorkingClient.getInstance().bindRouter(getActivity(), qrCode, new INetCallBack() {
            @Override
            public void onFinish(ResponseData response, @Nullable Object o) {
                if (response.isSuccess()) {

                    if (formLogin()){
                        showToast("绑定成功");
                        Intent data = new Intent();
                        data.putExtra(IntentExtra.EXTRA_BOOL, true);
                        setResult(Activity.RESULT_OK, data);
                        finish();
                    }
                }else {
                    mNext.setEnabled(false);
                    qrCode = null;
                    showToast(response.getMessage());
                }
            }
        });
    }

    @Override
    public void onScannerSuccess(String s) {
        qrCode = s;
        mNext.setEnabled(!TextUtils.isEmpty(s));

        if (formLogin()) {
            next();
        }
    }
}
